//解析导出的json数据
let msg = require('./msg.json');
let protobufRoot = require('protobufjs').Root;
let root = protobufRoot.fromJSON(msg);
let localConfig = require('./localConfig');

let parseData = {
    /**
     * 请求数据
     * @param req 
     * @param code 
     * @param data 
     * @returns 
     */
     reqData(req, code, data){
        let arryUti = this.encode(req, data);
        let arrayBuffer = new ArrayBuffer(4 + arryUti.length);
        let dataView = new DataView(arrayBuffer);
        dataView.setInt32(0,code);
        for (let i = 0; i < arryUti.length; i++) {
            dataView.setUint8(i+4, arryUti[i]);
        }
        return arrayBuffer;
    },

    /**
     * 返回数据
     * @param arrayBuffer 
     * @returns 
     */
     respData(arrayBuffer){
        // console.log('arrayBuffer>>>',arrayBuffer);
        let arrayBuffer1 = new Uint8Array(arrayBuffer);
        // console.log('arrayBuffer1>>>',arrayBuffer1);
        let dataView = new DataView(arrayBuffer1.buffer,0,4);
        let mid = dataView.getInt32(0);
        // console.log('mid>>>', mid);
        let buf = arrayBuffer1.subarray(4);//new Uint8Array(arrayBuffer,4);
        // console.log('buf>>>',buf);
        let deMessage = null;
        switch(mid){
            case localConfig.ProtoList.ChatMsg:
                deMessage = this.decode('Msg.ChatMsg',buf);
                break;
            default:
                console.warn('协议号未定义',mid);
                break
        }
        // console.log('deMessage>>>',deMessage);
        return {
            mid:mid,
            deMessage:deMessage
        };
    },

    /**
     * 序列化
     * @param {*} req 'login.LoginReq'
     * @param {*} infoData infoData = {uid:1}
     * @returns 
     */
    encode:function(req,infoData){
        let info = root.lookupType(req);
        let infoEncodeMessage = info.encode(info.create(infoData)).finish();
        return infoEncodeMessage;
    },
    /**
     * 反序列化
     * @param {*} infoEncodeMessage 
     * @returns 
     */
    decode:function(req,infoEncodeMessage){
        let info = root.lookupType(req);
        let infoUnSerialized = info.decode(infoEncodeMessage);
        return infoUnSerialized;
    },
    // 字符串转为ArrayBuffer对象，参数为字符串
    str2ab(str) {
        let buf = new ArrayBuffer(str.length); // 每个字符占用2个字节
        let bufView = new Uint8Array(buf);
        for (let i = 0, strLen = str.length; i < strLen; ++i) {
            bufView[i] = str.charCodeAt(i);
        }
        return buf;
    },
    //ArrayBuffer转为字符串
    ab2str(buf) {
        return String.fromCharCode.apply(null, new Uint8Array(buf));
    },
    //ArrayBuffer to Array
    arrayBufferToArray(arrayBuffer){
        let array = Array.prototype.slice.call(new Uint8Array(arrayBuffer ));
        return array;
    },
    //Array to ArrayBuffer
    arrayToArrayBuffer(array){
        let arrayBuffer = new Uint8Array(array).buffer;
        return arrayBuffer;
    }
}

module.exports = parseData;